﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }

    <link href="/css/AssemblyYield.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>AssemblyYield</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .hover-image {
            display: none;
            position: absolute;
            top: 20px;
            left: 0;
            width: 35vw;
            border: 1px solid #ccc;
            background: #fff;
            z-index: 999;
        }

        .warn-flag:hover .hover-image {
            display: block;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        #defect_input {
            width: 100%;
            padding: 0.05rem;
            font-size: 0.14rem;
            padding: 0.032rem;
            border: 1px solid #0aa9cd;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            transition: border-color 0.3s ease-in-out, box-shadow 0.3s ease-in-out;
            outline: none;
        }

        #defect_input:focus {
            border-color: #007BFF;
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .low {
            background-color: #ffff00;
        }

        .warning {
            background-color: #ffaf0078;
        }

        .danger {
            background-color: #ff1f0078;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }

        .process:hover {
            background-color: #b3f1fe;
        }

        /*END*/
        .truncate {
            /* max-width: 1.2rem; */
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        /*明细模态*/
        .show_mode {
            border-radius: 0.1rem;
            position: absolute;
            z-index: 99;
            height: 10.6rem;
            width: 100%;
            /*text-align: center;*/
            background: #a2c2e2;
            display: none;
        }

        .show_mode > .contentdetail > div {
            color: black;
            height: 33.3%;
            width: 50%;
            float: left;
            border-block: solid #ffffff 1px;
        }

        .show_mode > .contentdetail > div > label {
            color: black;
        }

        .detail {
            color: black;
            background-color: #f7fdff;
            height: 3rem;
            width: 100%;
        }

        .mode_close {
            float: right;
        }

        .mode_close:hover {
            background-color: #848690;
        }
        /*end*/

        #left-table-body, #charttab1, #plato_chart {
            background-image: url('../images/loading.gif');
            background-size: 0.8rem 0.8rem;
            background-repeat: no-repeat;
            background-position: center;
        }

        th, td {
            padding: 0.05rem;
            border: 1px solid #0bc4e9;
        }

        .popup {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 95%;
            background-color: white;
            box-shadow: 0 0 10px rgba(4, 193, 250,1);
            border-radius: 8px;
        }

        .defect_close:hover {
            background-color: #d2e9f8;
        }

        #defect_detail > thead > tr {
            height: 0.3rem;
            background-color: #0bc4e9;
        }

    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="AssemblyYieldExport('AssemblyYield')">@Label.Report@Label.Export</a>
                                <a class="menudropdown" onclick="AssemblyDetailToExcel('AssemblyDetail')">@Label.Data@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">
                        <span class="warn-flag" style="color:red; position: relative;">ℹ️<img src="../images/lot.png?v=@DateTime.Now.Ticks" class="hover-image" /></span>
                        @Label.Note_AssemblyYield
                    </div>
                    <div id="board" style="padding: 0.2rem 0.2rem;">
                        <div class="query">
                            <input type="datetime-local" id="startdate" name="startdate" placeholder="@Label.Start@Label.Time" style="width:1.9rem">
                            <span class="exampleInputProject tle">@Label.To</span>
                            <input type="datetime-local" id="enddate" name="enddate" placeholder="@Label.Start@Label.End" style="width:1.9rem">
                            <select id="cmb_prod_type" name="ProdType" placeholder="select prodtype">
                                <option value="ALL">@Label.ALL</option>
                                <option value="Normal">@Label.Fresh</option>
                                <option value="Rework">@Label.Rework</option>
                                <option value="RMA">@Label.RMA</option>
                            </select>
                            <select id="cmb_proj_code" placeholder="select ProjCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_product_code" placeholder="select ProductCode">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_process" placeholder="select Process">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="getdate()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <div id="left-table" class="rightTop">
                                <div id="left-table-body"></div>
                                <div class="popup">
                                    <span class="defect_close" style="font-size:0.15rem;color:red; float:right;font-weight:bold;" onclick="funclose()">关闭×</span>
                                    <div style="height:0.3rem">
                                        <span class="process_name" style="font-size:0.15rem;color:#007bff;font-weight:bold;line-height:0.3rem;padding-left: 0.15rem;"></span>
                                    </div>
                                    <div id="defect"></div>
                                </div>
                            </div>
                            <div id="right-table">
                                <div id="yield" class="rightTop">
                                    <div class="tab">
                                        <button class="tablinks active" onclick="OpenTab(event,'tab','charttab1',yieldfunction)">Yield&nbsp;Trend&nbsp;Chart</button>
                                        <button class="tablinks" onclick="OpenTab(event,'tab','charttab1',defect_chartfunction)">Defect&nbsp;Trend&nbsp;Chart</button>
                                        <button class="tablinks" onclick="OpenTab(event,'tab','charttab1',defectarea_chartfunction)">Defect&nbsp;Area&nbsp;Chart</button>
                                        <button class="tablinks" onclick="OpenTab(event,'tab','charttab1',defectByprocess_chartfunction)">Defect&nbsp;Distribution&nbsp;by&nbsp;Process</button>
                                        <div style="float: right; line-height:0.5rem;">
                                            <select id="cmb_data_type">
                                                <option value="MONTH">月</option>
                                                <option value="WEEK">周</option>
                                                <option value="DAY">天</option>
                                            </select>
                                        </div>
                                        <div class="search" style="float: right; line-height:0.5rem;display:none;">
                                            <input list="defect_search" id="defect_input" name="search" placeholder="请输入搜索的Defect...">
                                            <datalist id="defect_search" class="defect_search" style="height: calc(4.7rem - 0.12rem);"></datalist>
                                        </div>
                                    </div>
                                    <div id="charttab1" class="tabcontent"></div>
                                </div>
                                <div id="plato" class="rightTop">
                                    <div id="plato_chart"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="show_mode">
            <div style="width:100%; height:0.3rem;">
                <div class="mode_close" style="height:100%;margin-right:10px;line-height:0.3rem;">
                    <label style="font-size:0.17rem;color:white;">关闭&times;</label>
                </div>
            </div>
            <div class="contentdetail"></div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        $(".popup").css("display", "none");
        $(".search").css("display", "none");
        $(".show_mode").css("display", "none");
        $('.mode_close').click(function () {
            $(".show_mode").css("display", "none");
            $(".contentdetail").empty();
            $(".contentdetail div").remove();
        });

        function setDateRange(){
            var now = new Date();
            now.setMinutes(now.getMinutes() + 1);
            var hours = now.getHours();
            var minutes = now.getMinutes();

            var startDate = new Date();
            startDate.setDate(startDate.getDate() - 7);
            startDate.setHours(7, 0, 0, 0);
            var endDate = new Date();
            endDate.setHours(hours, minutes, 0, 0);
            var startdatetime = startDate.toLocaleDateString('sv-SE') + 'T' + startDate.toTimeString().slice(0,5)
            $('#startdate').val(startdatetime);
            var enddatetime = endDate.toLocaleDateString('sv-SE') + 'T' + endDate.toTimeString().slice(0,5)
            $('#enddate').val(enddatetime);
        }

        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_AssemblyYieldReport)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear();
                var myMonth = myDate.getMonth() + 1;
                var myToday = myDate.getDate();
                var myDay = myDate.getDay();
                var myHour = myDate.getHours();
                var myMinute = myDate.getMinutes();
                var mySecond = myDate.getSeconds();
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit + Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });

            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                if (endDate < startDate) {
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                if (startDate > endDate) {
                    $('#startdate').val($(this).val());
                }
            });
            setDateRange();
            ComboxAction();
            $('#cmb_proj_code').val('NCCSAD').trigger('change');
            $('#cmb_prod_type').val('ALL').trigger('change');
            $('#cmb_product_code').val('ALL').trigger('change');
            getdate();
        });
        //$(document).on('change', '#cmb_product_code,#cmb_process', function () {
        //    getdate();
        //});

        //定时查询
        setInterval(() => {
            console.log("执行任务：", new Date().toLocaleTimeString());
            setDateRange();
            getdate();
        }, 60 * 60 * 1000);

        /*Tab手动切换*/
        function OpenTab(evt, panle, id, echar_name, itemindex = -1) {
            $('#defect_input').val('ALL');
            $('#cmb_data_type').val('WEEK');
            var i, tablinks;
            tablinks = document.getElementsByClassName(panle)[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
            }
            evt.currentTarget.className += " active";
            let chart = echarts.init(document.getElementById(id));
            chart.dispose();
            echar_name();
        }

        var productprocess;
        var ComboxAction = function () {
            var projectsele = $("#cmb_proj_code");
            var productcode = $("#cmb_product_code");
            var process = $("#cmb_process");
            var pam = {};
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val()
            };
            loadData(projectsele, api + '/ReportAction/GetAssemblyProjCode', true);
            projectsele.change(function () {
                pam.proj_code = $(this).val();
                //pam.header_key = JSON.stringify(header_key);
                loadData(productcode, api + '/ReportAction/GetProductProcess', false);
            });
            productcode.change(function () {
                var processdt = productprocess.process.filter(item => item.product == $(this).val());
                Combox(processdt, process, false);
            });
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        if (url.includes("GetProductProcess")) {
                            selectdata = data.ReturnData.product;
                            productprocess = data.ReturnData;
                        }
                        else {
                            selectdata = data.ReturnData;
                        }
                        Combox(selectdata, selectElement, boolean);
                    }
                });
            }
            function Combox(selectdata, selectElement, boolean) {
                selectElement.empty();
                if (selectdata.length <= 0) {
                    @*selectElement.append("<option>@Html.Raw(Label.No + Label.Correlation + Label.Data)</option>");*@
                    selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                    return;
                }
                if (boolean) {
                    selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                } else {
                    selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                }
                $.each(selectdata, function (key, value) {
                    selectElement.append($('<option>', {
                        value: value.value,
                        text: value.text
                    }));
                });
            }
        }

        //报表导出
        var ExportType;
        var AssemblyYieldExport = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('prodtype', $('#cmb_prod_type').val());
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $('#cmb_product_code').val());
            formData.append('process_id', $('#cmb_process').val() == null ? "ALL" : $('#cmb_process').val());
            formData.append('excelname', ExportType);
            var url = api + "/ReportAction/GetAssemblyYieldToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }

        //原始数据导出
        var AssemblyDetailToExcel = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('start', $("#startdate").val());
            formData.append('end', $("#enddate").val());
            formData.append('prodtype', $('#cmb_prod_type').val());
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $('#cmb_product_code').val());
            formData.append('process_id', $('#cmb_process').val() == null ? "ALL" : $('#cmb_process').val());
            formData.append('excelname', type);
            var url = api + "/ReportAction/GetAssemblyDataToExcel";
            PostExportToExcel(url, formData);
            alert("数据量过大。。。\n\n正在加速下载，请等待2分钟^_^");
        }

        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }
        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send();
        }
        //合并相同行
        function mergeFunc(tableId) {
            var tab = document.getElementById(tableId);
            var maxCol = 3;//maxcol用于设置需要合并的列数
            var count, start;
            for (var col = maxCol - 1; col >= 0; col--) {
                //用于存储相同个数
                count = 1;
                for (var i = 0; i < tab.rows.length; i++) {
                    if (i > 0 && col > 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML
                        && tab.rows[i].cells[col - 1].innerHTML == tab.rows[i - 1].cells[col - 1].innerHTML) {
                        count++;
                    } else if (i > 0 && col == 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) {
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) {
                                tab.rows[j].removeChild(tab.rows[j].cells[col]);
                            }
                            count = 1;
                        }
                    }
                }
                if (count > 1) { //合并，最后几行相同的情况下
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].removeChild(tab.rows[j].cells[col]);
                    }
                }
            }
        }

        function loadingshow() {
            $('#left-table-body,#charttab1,#plato_chart').css('background-image', 'url("../images/loading.gif")');
            $('#left-table-body,#charttab1,#plato_chart').css('background-size', '0.8rem 0.8rem');
            $('#left-table-body,#charttab1,#plato_chart').css('background-repeat', 'no-repeat');
            $('#left-table-body,#charttab1,#plato_chart').css('background-position', 'center');
        }
        function loadingnone() {
            $('#left-table-body,#charttab1,#plato_chart').css('background-image', 'none');
        }

        //获取数据
        var Tab;
        var getdate = function () {
            $(".popup").css("display", "none");
            $('#cmb_data_type').val('WEEK');
            $('#btn_query').prop('disabled', true);
            var header_key = {
                start: $('#startdate').val(),
                end: $('#enddate').val(),
                prodtype: $('#cmb_prod_type').val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product_code').val();
            pam.process_id = $('#cmb_process').val();
            pam.header_key = JSON.stringify(header_key);
            if (pam.proj_code !== "-1") {
                loadingshow()
                $("#left-table-body").empty();
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetAssemblyYield",
                    data: pam,
                    dataType: "json",
                    success: function (dt) {
                        $('#btn_query').prop('disabled', false);
                        loadingnone();
                        Tab = dt.ReturnData;
                        defect_search_binding();
                        prod_yield_boarddata();
                        yieldfunction();
                        platofunction();
                    }
                });
            }
        }

        //defect绑定
        var defect_search_binding = function () {
            var defectSearch = $('#defect_search');
            defectSearch.empty();
            var DefectSet = new Set();
            $.each(Tab.Table4, function (index, item) {
                var DEFECT = item.DEFECT.trim();
                DefectSet.add(DEFECT);
            });
            defectSearch.append($('<option>').val('ALL'));
            DefectSet.forEach(function (DEFECT) {
                defectSearch.append($('<option>').val(DEFECT));
            });
            $('#defect_input').val('ALL');
        }

        var tablinksonclick = function (switch_on) {
            $('#cmb_data_type').val('WEEK');
            var i, tablinks;
            tablinks = document.getElementsByClassName('tab')[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].className = tablinks[i].className.replace("active", "");
                //console.log(tablinks[0].className.includes("active"));
            }
            switch (switch_on) {
                case "yield":
                    tablinks[0].className += " active";
                    $(".search").css("display", "none");
                    break;
                case "defect":
                    tablinks[1].className += " active";
                    $(".search").css("display", "block");
                    break;
                case "defectarea":
                    tablinks[2].className += " active";
                    $(".search").css("display", "block");
                    break;
                case "process":
                    tablinks[3].className += " active";
                    $(".search").css("display", "block");
                    break;
            }
        }

        //工序良率
        var prod_yield_boarddata = function () {
            $('#btn_query').prop('disabled', false);
            var data = Tab.Table.map(item => {
                let newItem = Object.assign({}, item);
                delete newItem.PRODUCT_SEQ;
                delete newItem.PROCESS_SEQ;
                return newItem;
            });
            $("#left-table-body").empty();
            var left_table_html = `
            <table id="myTable" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                <thead><tr></tr></thead>
                <tbody id="yield_tbody"></tbody>
                <tfoot><tr></tr></tfoot>
            </table>`;
            $("#left-table-body").append(left_table_html);
            var table = $('#myTable');
            var tbody = table.find('tbody');
            var headerRow = table.find('thead tr');
            var headers = Object.keys(data[0]);
            headers.forEach(function (header) {
                if(header != "HAVING_QTY"){
                    headerRow.append('<th>' + header + '</th>');
                }
            });
            data.forEach(function (row, index) {
                index++;
                var newRow = $(`<tr></tr>`);
                headers.forEach(function (header, columnindex) {
                    if (typeof row[header] === "number") {
                        if (header === "YIELD" ||  header === "YIELD_TARGET") {
                            row[header] = parseFloat(row[header]).toFixed(2) + '%';
                        } else {
                            row[header] = row[header].toFixed(0);
                        }
                    }
                    if (header === "PROCESS_ID") {
                        newRow.append(`<td class="truncate process" onclick="process_select('${row['PRODUCT_CODE']}','${row[header]}');"><a style="color:blue;font-weight:bolder;">${row[header]}</a></td>`);
                    } else {
                        if (header === "YIELD") {
                            var yieldVal = parseFloat(row[header].replace('%','')) || 0;
                            var targetVal = parseFloat(row.YIELD_TARGET) || 0;
                            //差值 = 目标 - 实际
                            var diff = targetVal - yieldVal; 
                            let cssClass = "";
                            if (diff > 5) {        //大于 5
                                cssClass = "danger";
                            } else if (diff > 3) { //3 - 5
                                cssClass = "warning";
                            } else if (diff > 0) { //0 - 3
                                cssClass = "low";
                            }
                            newRow.append(`<td class="truncate ${cssClass}">${row[header]}</td>`);
                        } else {
                            if (header === "DEFECT_QTY") {
                                let diffValue = parseInt(row.INPUT_QTY) - parseInt(row.OUTPUT_QTY);
                                let defectValue = parseInt(row.DEFECT_QTY);
                                let diffRate = (1 - defectValue / diffValue);
                                let cssClass = diffRate > 0.3 ? "warning" : "";
                                const count = parseInt(row.HAVING_QTY, 10) || 0;
                                const title = count ? `title="${count} 个缺陷属于【推力、调机、拉力、首件、中断】，不计入Yield统计⚠"`: "";
                                const titlespan = count ? `<span class="warn-flag" style="color:red;float:right;margin-right:0.2rem;" ${title}>&#9888;</span>` : "";
                                newRow.append(`<td class="truncate process ${cssClass}" onclick="defect_detail('${row['PRODUCT_CODE']}','${row['PROCESS_ID']}');" ${title}><a style="color:blue;font-weight:bolder;">${row[header]}</a>${titlespan}</td>`);
                            }
                            else{
                                if(header != "HAVING_QTY") {
                                    newRow.append(`<td class="truncate">${row[header]}</td>`);
                                }
                            }
                        }
                    }
                });
                tbody.append(newRow);
            });
            var colspan = 3;
            var tfootRow = table.find('tfoot tr');
            tfootRow.append(`<th colspan="${colspan}">汇总</th>`);
            //工序直通率（连乘）
            var fpyrate = data.reduce(function (acc, item) {
                var yieldVal = parseFloat(item.YIELD.replace('%','')) / 100 || 0;
                return acc * (yieldVal === 0 ? 1 : yieldVal);
            }, 1);

            //计算良率达标率
            var totalCount = data.length;
            var passCount = data.filter(function (row) {
                var yieldVal = parseFloat(row.YIELD.replace('%', '')) || 0;
                var targetVal = parseFloat(row.YIELD_TARGET) || 0;
                return yieldVal >= targetVal;
            }).length;
            var yieldTargetRate = totalCount > 0 ? ((passCount / totalCount) * 100).toFixed(2) + '%' : "0%";

            headers.forEach(function (header, columnindex) {
                if (columnindex >= colspan) {
                    var sum = 0;
                    data.forEach(function (row,index) {
                        sum = parseInt(row[header]) + sum;
                    });
                    if (header === "YIELD_TARGET") {
                        //显示工序达标率
                        sum = yieldTargetRate+'(达标率)';
                    }
                    if (header === "YIELD") {
                        //显示工序直通率
                        sum = (fpyrate * 100).toFixed(2) + '%'+'(直通率)';
                    }
                    if(header != "HAVING_QTY") {
                        tfootRow.append(`<th>${sum}</th>`);
                    }
                }
            });
        };

        function funclose (){
            $(".popup").css("display", "none");
            $("#defect").empty();
        }
        //sn_defect
        function defect_detail(product,process_id) {
            $(".process_name").text(`工序：${process_id}`);
            $(".popup").css("display", "none");
            $("#defect").empty();
            var data = Tab.Table1
                .filter(item => item.PROCESS_ID === process_id && item.PRODUCT_CODE === product)
                .map(item => {
                    let newItem = Object.assign({}, item);
                    delete newItem.PROJ_CODE;
                    delete newItem.PRODUCT_CODE;
                    delete newItem.PROCESS_ID;
                    return newItem;
                });
            if (data.length>0){
                $(".popup").css("display", "block");
                var defect_table_html = `
                <table id="defect_detail" style="margin: 0rem 0.15rem 0.15rem 0.15rem;width: calc(100% - 0.3rem);">
                    <thead><tr></tr></thead>
                    <tbody></tbody>
                </table>`;
                $("#defect").append(defect_table_html);
                var table = $('#defect_detail');
                var tbody = table.find('tbody');
                var headerRow = table.find('thead tr');
                var headers = Object.keys(data[0]);
                headers.forEach(function (header) {
                    headerRow.append('<th>' + header + '</th>');
                });
                var braNo = "style='text-align:center;background-color:#ffffff;'";
                var braTo = "style='text-align:center;background-color:#d2e9f8;'";
                data.forEach(function (row, index) {
                    index++;
                    var newRow = $(`<tr></tr>`);
                    var style = (index % 2) > 0 ? braNo : braTo;
                    headers.forEach(function (header, columnindex) {
                        newRow.append(`<td ${style} class="truncate">${row[header]}</td>`);
                    });
                    tbody.append(newRow);
                });
            }
            if (data.length>25)
            {
                $("#defect").css("height", "7rem");
                $("#defect").css("overflow-y", "auto");
            }else{
                $("#defect").css("height", "50%");
            }
        }

        var yieldchar;
        var yieldfunction = function () {
            tablinksonclick("yield");
            var chartData = Tab.Table6;
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            yieldchar = echarts.init(chartDom);
            updateChartOptions(chartData, null);
        };
        var updateChartOptions = function (chartData, dataZoomConfig) {
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.PROCESS_ID]) {
                    groupedData[item.PROCESS_ID] = {
                        TEST_TIME: [],
                        YIELD: []
                    };
                }
                groupedData[item.PROCESS_ID].TEST_TIME.push(item.TEST_TIME);
                groupedData[item.PROCESS_ID].YIELD.push(item.YIELD);
            });
            var seriesData = Object.keys(groupedData).map(function (processId) {
                return {
                    name: processId,
                    type: 'line',
                    data: groupedData[processId].YIELD.map(value => value === null ? 0 : value),
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + '%';
                        }
                    }
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        params.forEach(function (item) {
                            let dataItem = chartData.find(data => data.TEST_TIME == item.axisValue && data.PROCESS_ID == item.seriesName);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>Input: ${dataItem.INPUT}</td>
                                    <td>Output: ${dataItem.OUTPUT}</td>
                                    <td>Defect: ${dataItem.DEFECT_QTY}</td>
                                    <td>Yield: ${dataItem.YIELD}%</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '8%',
                    right: '3%',
                    bottom: '10%',
                    width: '89%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: chartData.map(item => item.TEST_TIME).filter((value, index, self) => self.indexOf(value) === index),
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Yield(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            yieldchar.setOption(option, true);
        };

        var platochar;
        var platooptionloop;
        var platofunction = function () {
            const group = {};
            Tab.Table4.forEach(item => {
                const defect = item.DEFECT;
                const qty = parseInt(item.DEFECT_QTY, 10);
                if (group[defect]) {
                    group[defect] += qty;
                } else {
                    group[defect] = qty;
                }
            });
            const chartData = Object.keys(group).map(defect => ({
                DEFECT: defect,
                DEFECT_QTY: group[defect]
            }));
            var DEFECTs = chartData.map(item => item.DEFECT);
            var DEFECT_QTY = chartData.map(item => parseFloat(item.DEFECT_QTY));
            var totalDEFECT_QTY = DEFECT_QTY.reduce((a, b) => a + b, 0);
            var cumulativeYield = [];
            var cumulativeSum = 0;
            DEFECT_QTY.forEach(function (value) {
                cumulativeSum += value;
                cumulativeYield.push(parseFloat((cumulativeSum / totalDEFECT_QTY * 100).toFixed(2)));
            });
            var chartDom = document.getElementById("plato_chart");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            platochar = echarts.init(chartDom);
            var option = {
                title: {
                    text: 'Defect Pareto',
                    textStyle: {
                        fontSize: '0.16rem',
                        color: '#0aa9cd'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    }
                },
                grid: {
                    top: '15%',
                    left: '7%',
                    right: '5%',
                    bottom: '20%',
                    width: '88%',
                },
                xAxis: {
                    type: 'category',
                    data: DEFECTs,
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisLabel: {
                        interval: DEFECTs.length >= 50 ? Math.ceil(DEFECTs.length / 50) : 0,
                        rotate: 45,
                        textStyle: {
                            fontSize: '0.14rem'
                        }
                    }
                },
                yAxis: [
                    {
                        type: 'value',
                        name: ' Defect Qty',
                        position: 'left',
                        nameTextStyle: {
                            fontSize: '0.14rem',
                            fontWeight: 'bold'
                        },
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: true
                        },
                        axisLabel: {
                            textStyle: {
                                fontSize: '0.14rem'
                            },
                            show: true
                        },
                        splitLine: {
                            show: false
                        }
                    },
                    {
                        type: 'value',
                        name: 'Proportion(%)',
                        position: 'right',
                        nameTextStyle: {
                            fontSize: '0.14rem',
                            fontWeight: 'bold'
                        },
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: true
                        },
                        axisLabel: {
                            formatter: function (value) {
                                return value + '%';
                            },
                            textStyle: {
                                fontSize: '0.14rem'
                            },
                            show: true
                        },
                        splitLine: {
                            show: false
                        }
                    }
                ],
                series: [
                    {
                        name: 'DefectQty',
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        },
                        data: DEFECT_QTY
                    },
                    {
                        name: 'Proportion',
                        type: 'line',
                        yAxisIndex: 1,
                        data: cumulativeYield,
                        itemStyle: {
                            color: '#FC8452',
                            Width: 2
                        },
                        itemStyle: { normal: { color: '#FC8452 ' } },
                        areaStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1,
                                    [
                                        { offset: 0, color: 'rgba(237, 178, 23, 0.5)' },
                                        { offset: 0.8, color: 'rgba(237, 178, 23, 0.1)' }
                                    ], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                                shadowBlur: 1
                            }
                        },
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + '%';
                            }
                        }
                    }
                ]
            };
            platochar.setOption(option);
            if (platooptionloop) {
                //platooptionloop.clearLoop();
                platooptionloop = null;
            }
            platooptionloop = tools.loopShowTooltip(platochar, option, { loopSeries: true });
        };
        var updatePlatoChart = function (product,process_id) {
            var filterData;
            if (process_id.toLowerCase() == "all") {
                filterData = Tab.Table4;
            }
            else {
                filterData = Tab.Table4.filter(function (item) { return item.PROCESS_ID === process_id && item.PRODUCT_CODE === product });
            }
            const group = {};
            filterData.forEach(item => {
                const defect = item.DEFECT;
                const qty = parseInt(item.DEFECT_QTY, 10);
                if (group[defect]) {
                    group[defect] += qty;
                } else {
                    group[defect] = qty;
                }
            });
            const chartData = Object.keys(group).map(defect => ({
                DEFECT: defect,
                DEFECT_QTY: group[defect]
            }));
            var DEFECTs = chartData.map(item => item.DEFECT);
            var DEFECT_QTY = chartData.map(item => parseFloat(item.DEFECT_QTY));
            var totalDEFECT_QTY = DEFECT_QTY.reduce((a, b) => a + b, 0);
            var cumulativeYield = [];
            var cumulativeSum = 0;
            DEFECT_QTY.forEach(function (value) {
                cumulativeSum += value;
                cumulativeYield.push(parseFloat((cumulativeSum / totalDEFECT_QTY * 100).toFixed(2)));
            });
            var itemcolor = [];
            var option = {
                xAxis: {
                    type: 'category',
                    data: DEFECTs,
                    axisLabel: {
                        interval: DEFECTs.length >= 50 ? Math.ceil(DEFECTs.length / 50) : 0,
                        rotate: 45
                    }
                },
                series: [
                    {
                        name: 'DefectQty',
                        data: DEFECT_QTY,
                        itemStyle: {
                            normal: {
                                barBorderRadius: [10, 10, 0, 0],
                                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                                    offset: 0,
                                    color: "#009AFD"
                                }, {
                                    offset: 0.8,
                                    color: "#33DAFF"
                                }], false),
                                shadowColor: 'rgba(0, 0, 0, 0.1)',
                            }
                        }
                    },
                    {
                        name: 'Proportion',
                        data: cumulativeYield
                    }
                ]
            };
            platochar.setOption(option);
        };

        //defect
        var defectchar;
        var defect_chartfunction = function () {
            $(".search").css("display", "block");
            tablinksonclick("defect");
            var chartData = Tab.Table9;
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            defectchar = echarts.init(chartDom);
            updateDefectChartOptions(chartData, null);
        };
        var updateDefectChartOptions = function (chartData, dataZoomConfig) {
            var uniqueTestTimes = chartData.map(item => item.TEST_TIME)
                .filter((value, index, self) => self.indexOf(value) === index)
                .sort((a, b) => a - b);
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.DEFECT]) {
                    groupedData[item.DEFECT] = {
                        TEST_TIME: [...uniqueTestTimes],
                        FAIL: new Array(uniqueTestTimes.length).fill(null)
                    };
                }
                var index = uniqueTestTimes.indexOf(item.TEST_TIME);
                groupedData[item.DEFECT].FAIL[index] = item.FAIL;
            });
            var seriesData = Object.keys(groupedData).map(function (defect) {
                return {
                    name: defect,
                    type: 'line',
                    data: groupedData[defect].FAIL.map(value => value === null ? 0 : value)
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let sortedParams = params.slice().sort((a, b) => b.data - a.data);
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        sortedParams.forEach(item => {
                            let dataItem = chartData.find(data => data.TEST_TIME == item.axisValue && data.DEFECT == item.seriesName);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>Input: ${dataItem.INPUT_QTY}</td>
                                    <td>DefectQty: ${dataItem.DEFECT_QTY}</td>
                                    <td>Fail: ${item.data}%</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '7%',
                    right: '3%',
                    bottom: '10%',
                    width: '90%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: uniqueTestTimes,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Fail(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    min: 0,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            defectchar.setOption(option, true);
        };

        //defectarea
        var defectareachar;
        var defectarea_chartfunction = function () {
            $(".search").css("display", "block");
            tablinksonclick("defectarea");
            var chartData = Tab.Table9;
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            defectareachar = echarts.init(chartDom);
            updateDefectAreaChartOptions(chartData, null);
        };
        var updateDefectAreaChartOptions = function (chartData, dataZoomConfig) {
            var uniqueTestTimes = chartData.map(item => item.TEST_TIME)
                .filter((value, index, self) => self.indexOf(value) === index)
                .sort((a, b) => a - b);
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.DEFECT]) {
                    groupedData[item.DEFECT] = {
                        TEST_TIME: [...uniqueTestTimes],
                        FAIL: new Array(uniqueTestTimes.length).fill(null)
                    };
                }
                var index = uniqueTestTimes.indexOf(item.TEST_TIME);
                groupedData[item.DEFECT].FAIL[index] = item.FAIL;
            });
            var colorList = [
                ['#80FFA5', '#00FF88'],
                ['#00DDFF', '#0096FF'],
                ['#37A2FF', '#188DF0'],
                ['#FF0087', '#FF5D77'],
                ['#FFBF00', '#FFD700'],
                ['#FF7F50', '#FF4500'],
                ['#FF6347', '#FF4500'],
                ['#FFA07A', '#FF6347'],
                ['#FFD700', '#FFBF00'],
                ['#FFC1C1', '#FF6A6A'],
                ['#FFA500', '#FF8C00'],
                ['#FFDAB9', '#FFC1C1']
            ];
            var seriesData = Object.keys(groupedData).map(function (defect, index) {
                var colorGradient = colorList[index % colorList.length];
                return {
                    name: defect,
                    type: 'line',
                    stack: 'Total',
                    smooth: false,
                    showSymbol: false,
                    lineStyle: { width: 0 },
                    emphasis: { focus: 'series'},
                    areaStyle: {
                        normal: {
                            opacity: 0.8,
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: colorGradient[0] },
                                { offset: 1, color: colorGradient[1] }
                            ])
                        }
                    },
                    data: groupedData[defect].FAIL.map(value => value === null ? 0 : value)
                };
            });
            var option = {
                color: Object.keys(groupedData).map(function (defect, index) {
                    return colorList[index % colorList.length][0];
                }),
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let sortedParams = params.slice().sort((a, b) => b.data - a.data);
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        sortedParams.forEach(item => {
                            let dataItem = chartData.find(data => data.TEST_TIME == item.axisValue && data.DEFECT == item.seriesName);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>Input: ${dataItem.INPUT_QTY}</td>
                                    <td>DefectQty: ${dataItem.DEFECT_QTY}</td>
                                    <td>Fail: ${item.data}%</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '7%',
                    right: '3%',
                    bottom: '10%',
                    width: '90%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: uniqueTestTimes,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Area Fail(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    min: 0,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            defectareachar.setOption(option, true);
        };

        //defect_By_process
        var defectByprocesschar;
        var defectByprocess_chartfunction = function () {
            $(".search").css("display", "block");
            tablinksonclick("process");
            var chartData = Tab.Table12;
            var chartDom = document.getElementById("charttab1");
            if (chartDom) {
                echarts.dispose(chartDom);
            }
            defectByprocesschar = echarts.init(chartDom);
            updateDefectByProcessChartOptions(chartData, null);
        };
        var updateDefectByProcessChartOptions = function (chartData, dataZoomConfig) {
            var groupedData = {};
            chartData.forEach(function (item) {
                if (!groupedData[item.PROCESS_ID]) {
                    groupedData[item.PROCESS_ID] = {};
                }
                groupedData[item.PROCESS_ID][item.TEST_TIME] = item.FAIL;
            });
            var uniqueTestTimes = chartData.map(item => item.TEST_TIME).filter((value, index, self) => self.indexOf(value) === index);
            var seriesData = Object.keys(groupedData).map(function (processId) {
                var failData = uniqueTestTimes.map(function (time) {
                    return groupedData[processId][time] || 0;
                });
                return {
                    name: processId,
                    type: 'line',
                    data: failData
                };
            });
            var option = {
                textStyle: {
                    fontSize: '0.16rem'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    textStyle: {
                        fontSize: '0.14rem'
                    },
                    axisPointer: {
                        type: 'cross',
                    },
                    formatter: function (params) {
                        let sortedParams = params.slice().sort((a, b) => b.data - a.data);
                        let tooltipText = `<div>${params[0].axisValue}</div><table>`;
                        sortedParams.forEach(function (item) {
                            let dataItem = chartData.find(data => data.TEST_TIME == item.axisValue && data.PROCESS_ID == item.seriesName);
                            if (dataItem) {
                                tooltipText += `
                                <tr>
                                    <td>${item.marker}${item.seriesName}</td>
                                    <td>Input: ${dataItem.INPUT_QTY}</td>
                                    <td>DefectQty: ${dataItem.DEFECT_QTY}</td>
                                    <td>Fail: ${item.data}%</td>
                                </tr>`;
                            }
                        });
                        tooltipText += '</table>';
                        return tooltipText;
                    }
                },
                legend: {
                    show: true,
                    type: 'scroll',
                    width: '100%',
                    data: Object.keys(groupedData),
                    orient: 'horizontal',
                    itemWidth: 12,
                    itemHeight: 12,
                    scrollDataIndex: 0,
                    pageIconSize: [16, 16],
                    pageIconColor: '#0aa9cd',
                    pageTextStyle: {
                        fontSize: '0.16rem',
                    },
                    textStyle: {
                        fontSize: '0.16rem'
                    }
                },
                grid: {
                    top: '20%',
                    left: '7%',
                    right: '3%',
                    bottom: '10%',
                    width: '90%',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: uniqueTestTimes,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Fail(%)',
                    position: 'left',
                    nameTextStyle: {
                        fontSize: '0.14rem',
                        fontWeight: 'bold'
                    },
                    scale: true,
                    axisTick: {
                        show: true
                    },
                    axisLabel: {
                        formatter: function (value) {
                            return value + '%';
                        },
                        textStyle: {
                            fontSize: '0.14rem'
                        },
                        show: true
                    }
                },
                series: seriesData,
                dataZoom: dataZoomConfig
            };
            defectByprocesschar.setOption(option, true);
        };

        //updateChart
        var updateTabChart = function (fun, actionname) {
            var defect = $('#defect_input').val();
            var cl_type = $('#cmb_data_type').val();
            if (!fun) return;
            var chartdata;
            var dataZoomConfig = [];
            const actionMap = {
                Yield: {
                    month: Tab.Table5,
                    week: Tab.Table6,
                    day: Tab.Table7,
                    updateFunc: updateChartOptions
                },
                Defect: {
                    month: Tab.Table10,
                    week: Tab.Table9,
                    day: Tab.Table8,
                    updateFunc: updateDefectChartOptions
                },
                DefectArea: {
                    month: Tab.Table10,
                    week: Tab.Table9,
                    day: Tab.Table8,
                    updateFunc: updateDefectAreaChartOptions
                },
                Process: {
                    month: Tab.Table13,
                    week: Tab.Table12,
                    day: Tab.Table11,
                    updateFunc: updateDefectByProcessChartOptions
                }
            };
            const commonDataZoomConfig = [
                {
                    type: 'inside',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1]
                },
                {
                    type: 'slider',
                    start: 0,
                    end: 100,
                    xAxisIndex: [0, 1],
                    handleSize: 0,
                    height: "0.3rem",
                    show: false,
                    zoomOnMouseWheel: true
                }
            ];
            for (let key in actionMap) {
                if (actionname == key) {
                    const actionConfig = actionMap[key];
                    chartdata = actionConfig[cl_type.toLowerCase()];
                    if (cl_type.toLowerCase() === 'day') {
                        dataZoomConfig = commonDataZoomConfig;
                    }
                    if (cl_type.toLowerCase() === 'month') {
                        updatePlatoChart('ALL','ALL');
                    }
                    if (actionname !== "Yield" && defect !== "ALL") {
                        chartdata = chartdata.filter(item => item.DEFECT == defect);
                    }
                    actionConfig.updateFunc(chartdata, dataZoomConfig);
                    break;
                }
            }
        };

        //defect下拉月周日页签联动
        $('#cmb_data_type,#defect_input').on('change', function () {
            var i, tablinks,fun, action;
            tablinks = document.getElementsByClassName("tab")[0].getElementsByClassName("tablinks");
            for (i = 0; i < tablinks.length; i++) {
                if (tablinks[i].className.includes("active")) {
                    switch (i) {
                        case 0:
                            action = "Yield";
                            fun = yieldchar;
                            break;
                        case 1:
                            action = "Defect";
                            fun = defectchar;
                            break;
                        case 2:
                            action = "DefectArea";
                            fun = defectareachar;
                            break;
                        case 3:
                            action = "Process";
                            fun = defectByprocesschar;
                            break;
                    }
                }
            }
            updateTabChart(fun,action);
        });
        //报表点击联动
        var process_select = function (product,process_id) {
            if (yieldchar.getDom()) {
                var legendData = yieldchar.getOption().legend[0].data;
                legendData.forEach(function (name) {
                    yieldchar.dispatchAction({
                        type: 'legendUnSelect',
                        name: name
                    });
                });
                yieldchar.dispatchAction({
                    type: 'legendSelect',
                    name: process_id
                });
            }
            if (platochar) {
                updatePlatoChart(product, process_id);
            }
        };
        window.addEventListener('resize', function () {
            [yieldchar, defectchar, defectareachar, defectByprocesschar, platochar].forEach(function (chart) {
                if (chart) {
                    setTimeout(chart.resize.bind(chart), 750);
                }
            });
        });

        //dataZoom 自动滚动
        var Zoom = function (id, myChart, option,data) {
            var autoScrollTimer;
            var scrollSpeed = 1;
            $(`#${id}`).mouseleave(function () {
                clearInterval(autoScrollTimer);
                autoScrollTimer = setInterval(function () {
                    var dataZoom = option.dataZoom[0];
                    var newStart = dataZoom.start + scrollSpeed;
                    var newEnd = dataZoom.end + scrollSpeed;
                    if (newEnd >= 100) {
                        newStart = 0;
                        newEnd = parseInt(30 / data.length * 100);
                    }
                    dataZoom.start = newStart;
                    dataZoom.end = newEnd;
                    myChart.setOption({
                        dataZoom: option.dataZoom
                    });
                }, 3000);
            });
            $(`#${id}`).mouseenter(function () {
                clearInterval(autoScrollTimer);
            });
        }
    </script>
</body>
</html>
